package com.saxon.mail;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class mail {
    //配置文件
    public static void main (String[] args) throws Exception {
        Properties properties = new Properties ();
        //准备
        properties.setProperty ("mail.host", "smtp.qq.com");//设置QQ邮箱
        properties.setProperty ("mail.transport.protocol", "smtp");//设置发送协议
        properties.setProperty ("mail.smtp.auth", "true");//是否验证密码
        //QQ邮箱

        MailSSLSocketFactory socketFactory = new MailSSLSocketFactory ();
        socketFactory.setTrustAllHosts (true);
        properties.put ("mail.smtp.ssl.enable", "true");
        properties.put ("mail.smtp.ssl.socketFactory", socketFactory);


        //邮箱的五个步骤
        //1.设置session环境
        Session defaultInstance = Session.getDefaultInstance (properties, new Authenticator () {
            @Override
            protected PasswordAuthentication getPasswordAuthentication () {
                return new PasswordAuthentication ("2433027822@qq.com", "ffvluhisjcfzebab");//前一个写地址，后一个写验证码
            }
        });
        defaultInstance.setDebug (true);
        //2获得transport对象.用来发送邮件
        Transport ts = defaultInstance.getTransport ();
        //3.使用邮箱和授权码来进行连接
        ts.connect ("smtp.qq.com", "2433027822#qq.com", "ffvluhisjcfzebab");
        //4,编写邮件
        Message message = new MimeMessage (defaultInstance);
        //指明发件人
        message.addRecipient (Message.RecipientType.TO, new InternetAddress ("2433027822@qq.com"));
        //设置主题
        message.setSubject ("你好啊");
        //设置图片内容
        MimeBodyPart image = new MimeBodyPart ();
        //图片要处理一下数据
        DataHandler dataHandler = new DataHandler (new FileDataSource ("D:\\dnf补丁\\bg.jpg"));
        image.setDataHandler (dataHandler);
        image.setContentID ("bg.jpg");//这里设置的ID我们子啊后面可以接着使用
        //准备正文数据
        MimeBodyPart content=new MimeBodyPart ();
        content.setContent ("这是一个带有图片的邮件<img src='uid:bg.jpg'>","text/html;charset=utf-8");
        //描述数据关系
        MimeMultipart mm=new MimeMultipart ();
        mm.addBodyPart (image);
        mm.addBodyPart (content);
        mm.setSubType ("related");
        message.setText ("这是第一份邮件");

        //设置到消息中
        message.setContent (mm);//把最后消息发送到消息中
        message.saveChanges ();//保存修改
        //设置接受的人
        message.setFrom (new InternetAddress ("2433027822@qq.com"));
        //5.发送邮件
        ts.sendMessage (message,message.getAllRecipients ());
        ts.close ();
    }

}
